<template>
  <div class="teachers-management">
    <!-- 搜索区域 -->
    <el-card class="filter-card">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="教师工号">
            <el-input v-model="filterForm.teacherId" placeholder="请输入教师工号" @keyup.enter="queryTeacherDetail" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item>
            <el-button type="primary" @click="queryTeacherDetail">查询</el-button>
            <el-button type="default" @click="resetFilter">重置</el-button>
            <el-button type="success" @click="addDialogVisible=true">添加教师</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-card>

    <el-dialog v-model="queryDialogVisible" title="教师信息查询结果" width="50%" @close="handleQueryDialogClose">
      <el-form :model="queryTeacherInfo" label-width="120px">
        <el-form-item label="教师工号">
          <el-input v-model="queryTeacherInfo.teacherId" disabled></el-input>
        </el-form-item>
        <el-form-item label="教师姓名">
          <el-input v-model="queryTeacherInfo.teacherName" disabled></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-input v-model="queryTeacherInfo.gender" disabled></el-input>
        </el-form-item>
        <el-form-item label="所属院系">
          <el-input v-model="queryTeacherInfo.department" disabled></el-input>
        </el-form-item>
        <el-form-item label="年龄">
          <el-input v-model="queryTeacherInfo.age" disabled></el-input>
        </el-form-item>
        <el-form-item label="联系电话">
          <el-input v-model="queryTeacherInfo.phone" disabled></el-input>
        </el-form-item>
        <el-form-item label="电子邮箱">
          <el-input v-model="queryTeacherInfo.email" disabled></el-input>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 教师列表 -->
    <el-card class="teacher-list-card">
      <div class="table-container">
        <el-table :data="teacherList" stripe border @row-dblclick="handleRowClick" style="width: 100%;" max-height="500px">
          <el-table-column prop="teacherId" label="教师工号" ></el-table-column>
          <el-table-column prop="teacherName" label="教师姓名" ></el-table-column>
          <el-table-column prop="gender" label="性别" width="80"></el-table-column>
          <el-table-column prop="department" label="所属院系" width="120"></el-table-column>
          <el-table-column prop="age" label="年龄" width="80"></el-table-column>
          <el-table-column prop="phone" label="联系电话" ></el-table-column>
          <el-table-column prop="email" label="电子邮箱" ></el-table-column>
          <el-table-column label="操作" >
            <template #default="scope">
              <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页组件 -->
      <el-pagination
          class="pagination"
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="pageSize"
          :current-page="currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 添加教师对话框 -->
    <el-dialog v-model="addDialogVisible" title="添加教师" width="50%" @close="handleAddDialogClose">
      <el-form :model="addForm" label-width="120px" :rules="addFormRules">
        <el-form-item label="教师工号" prop="teacherId">
          <el-input v-model="addForm.teacherId"></el-input>
        </el-form-item>
        <el-form-item label="教师姓名" prop="teacherName">
          <el-input v-model="addForm.teacherName"></el-input>
        </el-form-item>
        <el-form-item label="登录密码" prop="password">
          <el-input v-model="addForm.password" type="password" show-password></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="addForm.gender">
            <el-radio label="男">男</el-radio>
            <el-radio label="女">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="所属院系" prop="department">
          <el-input v-model="addForm.department"></el-input>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input-number v-model="addForm.age" :min="20" :max="80"></el-input-number>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="addForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="电子邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAddForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑教师对话框 -->
    <el-dialog v-model="editDialogVisible" title="编辑教师" width="50%" @close="handleEditDialogClose">
      <el-form :model="editForm" ref="editFormRef" label-width="120px" :rules="editFormRules">
        <el-form-item label="教师工号" prop="teacherId">
          <el-input v-model="editForm.teacherId" disabled></el-input>
        </el-form-item>
        <el-form-item label="教师姓名" prop="teacherName">
          <el-input v-model="editForm.teacherName"></el-input>
        </el-form-item>
        <el-form-item label="登录密码" prop="password">
          <el-input v-model="editForm.password" type="password" show-password :disabled="!changePassword"></el-input>
          <el-checkbox v-model="changePassword">修改密码</el-checkbox>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="editForm.gender">
            <el-radio label="男">男</el-radio>
            <el-radio label="女">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="所属院系" prop="department">
          <el-input v-model="editForm.department"></el-input>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input-number v-model="editForm.age" :min="20" :max="80"></el-input-number>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="editForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="电子邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEditForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, nextTick, computed, onMounted } from "vue";
import axios from "axios";
import { ElMessage, ElMessageBox } from "element-plus";

// 筛选条件
const filterForm = reactive({
  teacherId: "",
  teacherName: "",
  department: "",
});

// 表格数据和分页
const teacherList = ref([]);
const total = ref(0);
const pageSize = ref(10);
const currentPage = ref(1);

// 查询对话框相关
const queryDialogVisible = ref(false);
const queryTeacherInfo = ref({
  teacherId: "",
  teacherName: "",
  gender: "",
  department: "",
  age: "",
  phone: "",
  email: "",
});

//添加老师相关
const addDialogVisible = ref(false);
const addForm=ref({
  teacherId: "",
  teacherName: "",
  password: "",
  phone: "",
  email: "",
  gender: "",
  department: "",
  age: 0
})

//编辑老师相关
const editDialogVisible = ref(false);
const editForm=ref({
  teacherId: "",
  teacherName: "",
  password: "",
  phone: "",
  email: "",
  gender: "",
  department: "",
  age: 0
})
const changePassword = ref(false);
const editFormRef = ref(null);

const queryTeacherDetail = async () => {
  const teacherId = filterForm.teacherId;
  if (!teacherId) {
    ElMessage.warning("请输入教师工号");
    return;
  }
  try {
    const response = await axios.get(`/teachers/getTeacherDetail?teacherId=${teacherId}`);
    if (response.data.flag) {
      queryTeacherInfo.value = response.data.result;
      queryDialogVisible.value = true;
    } else {
      ElMessage.error(response.data.reason || "查询失败");
    }
  } catch (error) {
    console.error("查询出错:", error);
    ElMessage.error("查询时发生错误，请稍后重试");
  }
};

//确认添加
const submitAddForm = async () => {
  const formData = new FormData();
  formData.append("teacherId", addForm.value.teacherId);
  formData.append("department", addForm.value.department);
  formData.append("password", addForm.value.password);
  formData.append("teacherName", addForm.value.teacherName);
  if(addForm.value.phone){
    formData.append("phone", addForm.value.phone);
  }
  if(addForm.value.email){
    formData.append("email", addForm.value.email);
  }
  if(addForm.value.gender){
    formData.append("gender", addForm.value.gender);
  }
  if(addForm.value.age){
    formData.append("age", addForm.value.age);
  }

  try {
    const response = await axios.post('/teachers/addTeacher', formData);
    if(response.data.flag){
      ElMessage.success("添加成功");
      addDialogVisible.value = false;

      addForm.value = {
        teacherId: "",
        teacherName: "",
        password: "",
        phone: "",
        email: "",
        gender: "",
        department: "",
        age: 0,
      };

      fetchTeacherList();
    }else {
      ElMessage.error("添加失败：" + response.data.message || "未知错误");
    }
  }catch (error) {
    console.log(error);
    ElMessage.error("添加失败，请稍后重试");
  }
};

//编辑
const handleEdit=(row)=> {
  editDialogVisible.value = true;
  editForm.value={...row};
};

//提交编辑
const submitEditForm = async () => {
  await editFormRef.value.validate(async (valid) => {
    if(!valid){
      return;
    }
    const formData = new FormData();
    formData.append("teacherId", editForm.value.teacherId);
    formData.append("phone", editForm.value.phone);
    formData.append("email", editForm.value.email);
    if(editForm.value.teacherName){
      formData.append("teacherName", editForm.value.teacherName);
    }
    if(editForm.value.gender){
      formData.append("gender", editForm.value.gender);
    }
    if(editForm.value.department){
      formData.append("department", editForm.value.department);
    }
    if(editForm.value.age){
      formData.append("age", editForm.value.age);
    }
    if(changePassword.value){
      formData.append("password", editForm.value.password);
    }

    try {
      const response = await axios.post(`/teachers/updateTeacher`, formData);
      if(response.data.flag){
        ElMessage.success("教师信息更新成功！");
        editDialogVisible.value = false;
        editFormRef.value.resetFields();
        fetchTeacherList();

      }else {
        ElMessage.error("更新失败！");
      }
    }catch (error) {
      console.log(error);
    }
  })
};

// 重置筛选条件
const resetFilter = () => {
  filterForm.teacherId = "";
  filterForm.teacherName = "";
  filterForm.department = "";
  fetchTeacherList();
};
// 添加表单验证规则
const addFormRules = computed(() => ({
  teacherId: [
    { required: true, message: "请输入教师工号", trigger: "blur" },
    { len:8, message: "长度:8个字符", trigger: "blur" }
  ],
  teacherName: [
    { required: true, message: "请输入教师姓名", trigger: "blur" }
  ],
  password: [
    { required: true, message: "请输入登录密码", trigger: "blur" },
    { min: 6, message: "密码长度至少为6位", trigger: "blur" }
  ],
  department: [
    { required: true, message: "请输入所属院系", trigger: "blur" }
  ],
  email: [
    { type: "email", message: "请输入正确的邮箱格式", trigger: ["blur", "change"] }
  ],
}));

// 编辑表单验证规则
const editFormRules = computed(() => ({
  teacherName: [
    { required: true, message: "请输入教师姓名", trigger: "blur" }
  ],
  password: [
    { required: changePassword.value, message: "请输入登录密码", trigger: "blur" },
    { min: 6, message: "密码长度至少为6位", trigger: "blur" }
  ],
  department: [
    { message: "请输入所属院系", trigger: "blur" }
  ],
  email: [
    {  required: true,type: "email", message: "请输入正确的邮箱格式", trigger: ["blur", "change"] }
  ],
  phone: [
    { required: true, message: "请输入联系电话", trigger: "blur" }
  ]
}));

// 生命周期钩子
onMounted(async () => {
  await fetchTeacherList();
});

// 获取教师列表
const fetchTeacherList = async () => {
  try {
    // const params = {
    //   ...filterForm,
    //   page: currentPage.value,
    //   size: pageSize.value,
    // };
    const formData = new FormData();
    formData.append("department",filterForm.department);
    formData.append("teacherId",filterForm.teacherId);
    formData.append("teacherName",filterForm.teacherName);
    formData.append("page",currentPage.value);
    formData.append("size",pageSize.value)
    const response = await axios.post("/teachers/getTeacherList", formData);
    teacherList.value = response.data.result || [];
    total.value = response.data.total || 0;
  } catch (error) {
    console.error("获取教师列表失败", error);
    ElMessage.error("获取教师列表失败，请稍后重试");
  }
};

const handleQueryDialogClose = () => {
  queryDialogVisible.value = false;
  queryTeacherInfo.value = {
    teacherId: "",
    teacherName: "",
    gender: "",
    department: "",
    age: "",
    phone: "",
    email: "",
  };
};

// 添加对话框关闭时处理
const handleAddDialogClose = () => {
  addDialogVisible.value = false;
};

// 编辑对话框关闭时处理
const handleEditDialogClose = () => {
  editDialogVisible.value = false;
  editForm.value = {}; // 重置表单对象
  changePassword.value = false; // 重置密码修改标记
};

// 删除教师
const handleDelete = (teacher) => {
  ElMessageBox.confirm(
      `确定要删除教师 "${teacher.teacherName}" (${teacher.teacherId}) 吗？删除后将无法恢复。`,
      "提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "danger",
      }
  ).then(async () => {
    try {
      const response = await axios.delete(`/teachers/deleteTeacher?teacherId=${teacher.teacherId}`);
      if (response.data.flag) {
        ElMessage.success("教师删除成功");
        fetchTeacherList();
      } else {
        ElMessage.error(response.data.message || "教师删除失败");
      }
    } catch (error) {
      console.error("删除教师失败", error);
      ElMessage.error("删除教师失败，请稍后重试");
    }
  }).catch(() => {
    // 取消操作
  });
};

// 双击行编辑
const handleRowClick = (row) => {
  handleEdit(row.teacherId);
};

// 分页控制
const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  fetchTeacherList();
};

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  fetchTeacherList();
};
</script>

<style scoped>
.teachers-management {
  padding: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

teacher-list-card {
  height: auto;
  margin-bottom: 20px;
}

.table-container {
  height: 500px;
  overflow-y: auto;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>